/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-3-20 16:59:53
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#ifndef INCLUDE_RPC_SERVER_MGR_H_
#define INCLUDE_RPC_SERVER_MGR_H_

#include "base/xrefptr.h"
#include "base/xmutex.h"
#include "base/xguard.h"
#include "base/xthread.h"
#include "net/net_reactor.h"
#include "protocol/net_binary_decoder.h"
#include "protocol/net_proto_def.h"
#include <map>


class CRpcServerBase;
class RpcBeanMap;
class CRpcServerMgr : public IEvent_handler
{
    friend class CRpcServerBase;
    friend class RpcBeanMap;
    CRpcServerMgr( const CRpcServerMgr& );
    const CRpcServerMgr& operator= ( const CRpcServerMgr& );
public:
    CRpcServerMgr();
    CRpcServerMgr(int threadnum);
    virtual ~CRpcServerMgr();
    
public:
    void free();
protected:
    smart::ref_ptr<CRpcServerBase> get_rpc_server( SOCK_FD listenfd );
    int add_rpc_server( CRpcServerBase* server );
    int del_rpc_server( SOCK_FD listenfd );
    void del_all_rpc_server();
    
    SOCK_FD get_listenfd_from_kv( SOCK_FD cli_fd );
    int add_kv( SOCK_FD cli_fd, SOCK_FD listen_fd );
    int del_kv( SOCK_FD cli_fd );
    void del_all_kv();
    
    int close_fd( SOCK_FD fd );
private:
    virtual int on_connect( SOCK_FD listen_fd, SOCK_FD cli_fd, const char* remote_ip, int remote_port );
	virtual int on_data( SOCK_FD fd, const char* data, int len, const char* remote_ip, int remote_port );
	virtual int on_send_ack( SOCK_FD fd, int len );
	virtual int on_close( SOCK_FD fd, int error );
private:
    net_reactor_t m_netReactor;
    std::map< SOCK_FD, smart::ref_ptr<CRpcServerBase> > m_rpc_servers_map;
    smart::mutex_t m_lock;
    std::map< SOCK_FD, SOCK_FD > m_kv_map; //cli_fd --> listen_fd
    smart::mutex_t m_kv_lock;
};


#endif //~INCLUDE_RPC_SERVER_MGR_H_

